package com.ruoyi.project.weixinCheck;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.project.system.user.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping ("/wx")
public class WeixinCheckController {



    @Autowired
    private UserMapper userMapper;

    private static final Logger LOGGER = LoggerFactory.getLogger(WeixinCheckController.class);

    @RequestMapping (method = RequestMethod.GET)
    public Long checkToken (HttpServletRequest request, HttpServletResponse response) {
        LOGGER.error("微信的请求:" + request.getParameterMap().toString());
        // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        String signature = request.getParameter("signature");
        LOGGER.error("微信加密签名:" + signature);
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        LOGGER.error("时间戳:" + timestamp);
        // 随机数
        String nonce = request.getParameter("nonce");
        LOGGER.error("随机数:" + nonce);
        // 随机字符串
        String echostr = request.getParameter("echostr");
        LOGGER.error("随机字符串:" + echostr);

 /*       PrintWriter out = null;
        try {
            out = response.getWriter();
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，否则接入失败
            if (WeixinCheckoutUtil.checkSignature(signature, timestamp, nonce)) {
                LOGGER.info("微信加密签名:" + signature + ";时间戳:" + timestamp + ";随机数:" + nonce+ ";随机字符串:" + echostr);
                out.print(echostr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
            out = null;
        }*/
        return Long.parseLong(echostr);
    }

    @RequestMapping (method = RequestMethod.POST)
    public String push (@RequestBody String body) {
        LOGGER.error("微信的push请求:" + body);
        WxBean wxBean = JSONObject.parseObject(body, WxBean.class);
        if("user_authorization_revoke".equals(wxBean.getEvent())){


            return "success";
        }else {
            return "error";
        }
    }
}